package com.talent.jiwen.wrongbook;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.wrongbook.ErrorBookBean;
import com.talent.jiwen.http.result.tiku.Question;
import com.talent.jiwen.ui.widgets.MyGridView;
import com.talent.jiwen.util.GsonUtil;
import com.talent.jiwen.util.MyToast;
import com.talent.jiwen.util.Validators;
import com.talent.jiwen.wrongbook.data.WrongSingleData;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;

public class WrongDetailActivity extends BaseActivity {
    @BindView(R.id.sourceTv)
    TextView sourceTv;
    @BindView(R.id.chapterTv)
    TextView chapterTv;
    @BindView(R.id.difficultTv)
    TextView difficultTv;
    @BindView(R.id.questionWebView)
    WebView questionWebView;
    @BindView(R.id.historyAnswerTv)
    TextView historyAnswerTv;
    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    @BindView(R.id.answerWebView)
    WebView answerWebView;
    @BindView(R.id.cantTv)
    TextView cantTv;
    @BindView(R.id.littleTv)
    TextView littleTv;
    @BindView(R.id.underStandTv)
    TextView underStandTv;
    @BindView(R.id.practiceTv)
    TextView practiceTv;

    public static final String PARAM_SUBJECT_ID = "param.subject.id";
    public static final String PARAM_SUBJECT_NAME = "param.subject.name";
    public static final String PARAM_HOMEWORK_TYPE = "param.homework.type";
    public static final String PARAM_HOMEWORK_ID = "param.homeworkId";
    public static final String PARAM_ERROR_SINGLE_BEAN = "param.error.single.bean";

    private String subjectId;
    private String subjectName;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_wrong_detail;
    }

    @Override
    public String titleName() {
        return getString(R.string.wrong_detail);
    }

    @Override
    protected void initData() {
        subjectId = getIntent().getIntExtra(PARAM_SUBJECT_ID, 0) + "";
        int homeWorkType = getIntent().getIntExtra(PARAM_HOMEWORK_TYPE , 1);
        int homeWorkId = getIntent().getIntExtra(PARAM_HOMEWORK_ID , 0);
        String singleDataStr = getIntent().getStringExtra(PARAM_ERROR_SINGLE_BEAN);
        if (!Validators.isEmpty(singleDataStr)){
            WrongSingleData singleBean = GsonUtil.getInstance().json2Bean(singleDataStr , WrongSingleData.class);
            configSingleData(homeWorkType , singleBean);
        }
    }

    @OnClick({R.id.cantTv, R.id.littleTv, R.id.underStandTv, R.id.practiceTv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cantTv:
                break;
            case R.id.littleTv:
                break;
            case R.id.underStandTv:
                break;
            case R.id.practiceTv:
                break;
        }
    }

    private void configSingleData(int  homeWorkType , WrongSingleData wrongSingleData){
        if (homeWorkType == 3) {
//            //错题照片
//            if (startIndex == 0 && null == errorSingleBean.getWrongImageInfo()) {
//                contentLayout.setVisibility(View.GONE);
//                noRecordIv.setVisibility(View.VISIBLE);
//            } else {
//                contentLayout.setVisibility(View.VISIBLE);
//                noRecordIv.setVisibility(View.GONE);
//            }
//            if (startIndex == 0) {
//                errorImgBeanList.clear();
//            }
//            errorImgBeanList.add(errorSingleBean.getWrongImageInfo());
//            ErrorImgBean imgBean = errorSingleBean.getWrongImageInfo();
//            setPracticeBean(imgBean.getSubjectId() , imgBean.getSubjectName() , imgBean.getCategoryId() , imgBean.getCategoryName()
//                    , imgBean.getGradeId() , imgBean.getGradeName() , imgBean.getChapterId() , imgBean.getChapterName()
//                    , imgBean.getQuestionTypeId() , imgBean.getQuestionTypeName() , imgBean.getDifficultyLevelId() , imgBean.getDifficultyLevelName());
//            hasMore = false;
//
//            //刷新列表
//            if (null == fragmentPagerAdapter) {
//                errorFilter.setHomeworkType(3);
//                initReadViewPager();
//            } else {
//                fragmentPagerAdapter.notifyDataSetChanged();
//            }

        } else {
            //题库错题
            ErrorBookBean bookBean = wrongSingleData.getWrongHomeworkInfo();
            getTimu(bookBean);
        }

    }


    /**
     * 设置掌握程度显示
     *
     * @param underStand
     */
    private void configUnderStand(String underStand) {
        if (underStand.equals(cantTv.getText().toString()) || Validators.isEmpty(underStand)) {
            cantTv.setTextColor(ContextCompat.getColor(this, R.color.white));
            cantTv.setBackgroundResource(R.drawable.bg_wrong_tag_orange_sel);
            littleTv.setTextColor(ContextCompat.getColor(this, R.color.lightsalmon));
            littleTv.setBackgroundResource(R.drawable.bg_wrong_tag_orange);
            underStandTv.setTextColor(ContextCompat.getColor(this, R.color.lightsalmon));
            underStandTv.setBackgroundResource(R.drawable.bg_wrong_tag_orange);
        } else if (underStand.equals(littleTv.getText().toString())) {
            cantTv.setTextColor(ContextCompat.getColor(this, R.color.lightsalmon));
            cantTv.setBackgroundResource(R.drawable.bg_wrong_tag_orange);
            littleTv.setTextColor(ContextCompat.getColor(this, R.color.white));
            littleTv.setBackgroundResource(R.drawable.bg_wrong_tag_orange_sel);
            underStandTv.setTextColor(ContextCompat.getColor(this, R.color.lightsalmon));
            underStandTv.setBackgroundResource(R.drawable.bg_wrong_tag_orange);
        } else if (underStand.equals(underStandTv.getText().toString())) {
            cantTv.setTextColor(ContextCompat.getColor(this, R.color.lightsalmon));
            cantTv.setBackgroundResource(R.drawable.bg_wrong_tag_orange);
            littleTv.setTextColor(ContextCompat.getColor(this, R.color.lightsalmon));
            littleTv.setBackgroundResource(R.drawable.bg_wrong_tag_orange);
            underStandTv.setTextColor(ContextCompat.getColor(this, R.color.white));
            underStandTv.setBackgroundResource(R.drawable.bg_wrong_tag_orange_sel);
        }
    }


    /** 获取题目
     *
     * @param bookBean
     */
    private void getTimu(final ErrorBookBean bookBean) {

        Observable observable = ApiFactory.getTiKuApiSingleton().getQuestionByIds(bookBean.getHomeworkId() + "");

        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<List<Question.DataBean>>(this) {
                    @Override
                    protected void _onNext(List<Question.DataBean> listData) {
                        //将获取到的题目保存到集合
                        if (!Validators.isEmpty(listData)){
                            Question.DataBean dataBean = listData.get(0);
                            if (null != bookBean.getStudentHistoryAnswers()){
                                dataBean.setMoreQuestion(Arrays.asList(bookBean.getStudentHistoryAnswers()));
                            }

                            if (Validators.isEmpty(bookBean.getChapterName())){
                                chapterTv.setVisibility(View.GONE);
                            }else{
                                chapterTv.setVisibility(View.VISIBLE);
                                String chapterName = bookBean.getChapterName();
                                if (chapterName.length() > 15){
                                    chapterName = chapterName.substring(0 , 15) + "...";
                                }
                                chapterTv.setText(chapterName);
                            }
                            if (Validators.isEmpty(bookBean.getDifficultyLevelName())){
                                difficultTv.setVisibility(View.GONE);
                            }else{
                                difficultTv.setVisibility(View.VISIBLE);
                                difficultTv.setText(bookBean.getDifficultyLevelName());
                            }
                            if (Validators.isEmpty(ErrorBookBean.getSourceName(bookBean.getHomeworkType()))){
                                sourceTv.setVisibility(View.GONE);
                            }else{
                                sourceTv.setVisibility(View.VISIBLE);
                                sourceTv.setText(ErrorBookBean.getSourceName(bookBean.getHomeworkType()));
                            }
                            configUnderStand(ErrorBookBean.getLevelName(bookBean.getMasterLevel()));
                            initQuestion(dataBean);
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        MyToast.show(WrongDetailActivity.this, getString(R.string.no_result_data));

                    }
                }
                , ActivityLifeCycleEvent.DESTROY, lifecycleSubject, true);
    }

    private void initQuestion(final Question.DataBean data){
        questionWebView.loadDataWithBaseURL(null, data.getTmhtm(), "text/html", "utf-8", "");
        String text = "";
        if (data.getDahtm() == null) {
            text = "正确答案： 暂无" + "</br>" + "解析：" + data.getJxhtm();
        } else {
            if(data.getTixin().equals("判断")){
                String judge = data.getDahtm();

                if (judge.equals("√") || judge.equals("1") || judge.equals("T")) {
                    text = "正确答案：正确"  + "</br>" + "解析：" + data.getJxhtm();
                }else{
                    text = "正确答案：错误"  + "</br>" + "解析：" + data.getJxhtm();
                }

            }else{
                text = "正确答案：" + data.getDahtm() + "</br>" + "解析：" + data.getJxhtm();
            }
        }
        answerWebView.loadDataWithBaseURL(null, text, "text/html", "utf-8", "");

        if (Validators.isEmpty(data.getMoreQuestion())){
            historyAnswerTv.setVisibility(View.GONE);
            recycleView.setVisibility(View.GONE);
        }else{
            historyAnswerTv.setVisibility(View.VISIBLE);
            recycleView.setVisibility(View.VISIBLE);
            LinearLayoutManager layoutManager = new LinearLayoutManager(this);
            recycleView.setLayoutManager(layoutManager);
            recycleView.setAdapter(new CommonAdapter<String>(WrongDetailActivity.this , R.layout.item_wrong_detail_answer , data.getMoreQuestion()){
                @Override
                protected void convert(ViewHolder holder, String s, int position) {
                    TextView answerTv = holder.getView(R.id.answerTv);
                    MyGridView gridView = holder.getView(R.id.gridView);

                    answerTv.setVisibility(View.GONE);
                    gridView.setVisibility(View.GONE);

                    String content = data.getMoreQuestion().get(position);
                    if (Validators.isEmpty(content)){
                        answerTv.setVisibility(View.VISIBLE);
                        gridView.setVisibility(View.GONE);

                        answerTv.setText("未做");
                    } else if (content.contains(",,")){
                        String[] splits = content.split(",,");
                        if (splits.length > 1){
                            String split1 = splits[0];
                            String split2 = splits[1];
                            setContent(split1 , gridView , answerTv);
                            setContent(split2, gridView , answerTv);
                        }else{
                            String split = splits[0];
                            setContent(split, gridView , answerTv);
                        }
                    }else{
                        setContent(content, gridView , answerTv);
                    }
                }
            });
        }
    }


    private void setContent(String content , MyGridView gridView , TextView answerTv){
        if (content.startsWith("[\"http") && content.endsWith("]")){
            //图片
            String[] array = new Gson().fromJson(content , String[].class);
            List<String> imgList = new ArrayList<>();
            imgList.clear();
            imgList.addAll(Arrays.asList(array));

            gridView.setVisibility(View.VISIBLE);
            ImageAdapter adapter = new ImageAdapter(imgList);
            gridView.setAdapter(adapter);

        }else{
            //文字
            answerTv.setVisibility(View.VISIBLE);
            answerTv.setText(content);
        }
    }

    public class ImageAdapter extends BaseAdapter{
        private List<String> contentList;

        public ImageAdapter(List<String> contentList) {
            this.contentList = contentList;
        }

        @Override
        public int getCount() {
            return contentList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            if (null == view){
                view = LayoutInflater.from(mContext).inflate(R.layout.item_wrong_answer_img , null);
            }
            ImageView imageView = (ImageView)view.findViewById(R.id.imgIv);
            String url = contentList.get(i);
            Glide.with(mContext).load(url).into(imageView);

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            });
            return view;
        }
    }
    /**单个题目
     *
     * @param context
     * @param homeworkId
     * @param homeworkType
     */
    public static void startErrorBookSingleActivity(Context context, int homeworkId, int homeworkType , WrongSingleData data) {
        Intent intent = new Intent(context, WrongDetailActivity.class);
        if (data.getWrongHomeworkInfo() != null){
            intent.putExtra(WrongDetailActivity.PARAM_SUBJECT_ID , data.getWrongHomeworkInfo().getSubjectId());
        }else{
            intent.putExtra(WrongDetailActivity.PARAM_SUBJECT_ID , data.getWrongImageInfo().getSubjectId());
        }
        intent.putExtra(WrongDetailActivity.PARAM_HOMEWORK_ID , homeworkId);
        intent.putExtra(WrongDetailActivity.PARAM_HOMEWORK_TYPE ,homeworkType);
        intent.putExtra(WrongDetailActivity.PARAM_ERROR_SINGLE_BEAN , GsonUtil.getInstance().toJson(data));
        context.startActivity(intent);
    }
}
